package com.dognessnetwork.operation.ops.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;

import com.dognessnetwork.operation.baseservice.MessagesService;
import com.dognessnetwork.operation.ops.domain.Messages;
import com.dognessnetwork.operation.ops.repository.MessagesRepository;

@Service
public class MessagesServiceImpl implements MessagesService {
	
	/*private final   Logger  log =   LoggerFactory.getLogger(getClass());
    */
    @Autowired
    private	MessagesRepository	messagesRepository;
    
    @Bean
    public	MessagesRepository	getMessagesRepository(){
    	return	messagesRepository;
    }

	@Override
	public Messages save(Messages messages) {
		// TODO Auto-generated method stub
		messages.setSendTime(dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
		return getMessagesRepository().save(messages);
	}
	
	/**
     * 获取未回复的用户
     * @return
     */
	@Override
	public	List<Object>	getUserList(boolean	sender){
		return getMessagesRepository().queryUserlist();
	}

	@Override
	public List<Messages> getMessageHistory(String userIdCard,Pageable pageable) {
		// TODO Auto-generated method stub
		
		List<Messages> messages = getMessagesRepository().findByUserIdCardOrderBySendTimeAsc(userIdCard, pageable).getContent();
		return messages;
	}
	

	@Override
	public int queryMessagesById(@Param("id") Long id,@Param("receiveTime") String receiveTime) {
		return getMessagesRepository().queryMessagesById(id, dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
	}
	public String dateToStr(Date date, String strFormat) {
	    SimpleDateFormat sf = new SimpleDateFormat(strFormat);
	    String str = sf.format(date);
	    return str;
	}
	@Override
	public List<Object[]> getMessagesByUserIdCard(@Param("userIdCard")String userIdCard) {
		// TODO Auto-generated method stub
		return getMessagesRepository().queryMessagesByUserIdCard(userIdCard);
	}

	@Override
	public int findMessageCountByUserIdCard(@Param("userIdCard")String userIdCard) {
		int count = getMessagesRepository().queryCountMessages(userIdCard);
		return count;
	}

	@Override
	public List<Messages> getAnswer(Long id, String userIdCard) {
		List<Messages> messages = getMessagesRepository().queryAnswer(id, userIdCard);
		return messages;
	}

	@Override
	public int queryMaxMessageId(String userIdCard) {
		int id = getMessagesRepository().queryMaxMessageId(userIdCard);
		return id;
	}

	@Override
	public Messages findById(Long id) {
		Messages messages = getMessagesRepository().findOne(id);
		return messages;
	}
}
